<?php
namespace Library;

/**
 * 区域管理类
 *
 * @author pufan
 */
class Area {
    private static $_instance;
    protected $region;
    
    private function __construct() {
        $this->region = D("region");
    }
    
    public function __clone() {
        trigger_error('Clone is not allow!', E_USER_ERROR);
    }
    
    public static function getInstance(){
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        
        return self::$_instance;
    }

    //SELECT a.id, a.name, a.code, a.parent_id, b.id  FROM yy_region a LEFT JOIN yy_region b ON a.parent_id=b.code
    function getThreeRegions() {
        S('three_regions:', NULL);
        $regions = S('three_regions:');
        if ($regions) {
            return $regions;
        }

        $firstRegion = $this->region->where('parent_id = 0')->getField('id, name, shortname,  code');

        foreach ($firstRegion as $key => $value) {
            $secondRegion = $this->region->where('parent_id = '.$value['code'])->getField('id, name, shortname, code');
            foreach ($secondRegion as $ke => $val) {
                $thirdRegion = $this->region->where('parent_id = '.$val['code'])->getField('id, name, shortname,  code');
                $secondRegion[$ke]['lower'] = $thirdRegion;
            }
            $firstRegion[$key]['lower'] = $secondRegion;
        }

        S('three_regions:', $firstRegion);


        return $firstRegion;
    }
}
